#!/usr/bin/env python3

if False:"""

FOR: quick olap example
AUTHOR: Wanjo
DATE:2022-06-25
WARNING: quick dev only, don't try go production.

# download websocketd.zip
curl -L -o ~/wsd.zip https://github.com/joewalnes/websocketd/releases/download/v0.3.0/websocketd-0.3.0-linux_amd64.zip
# extract to ~
unzip ~/wsd.zip -d ~
# or
curl -L -o - https://github.com/joewalnes/websocketd/releases/download/v0.3.0/websocketd-0.3.0-linux_amd64.zip | unzip > ~/websocketd

# start server
~/websocketd -port 8444 ./svr_olap.py
%USERPROFILE%\websocketd -port 8444 python svr_olap.py

# try client
python clt_ws.py 8444
"""

from mypy import sys,tryx,now,o2s,re_match,time_maker

######################################
def count_by_code(code):
  import duckdb
  sql = f"select count(*) c from '../../tmp/raw/{code}/*.parquet'"
  return duckdb.query(sql).df().to_dict()

def sample_by_code(code,limit=99,dump=True):
  #if not re_match('[0-9A-Z\.]*',code): return code
  import duckdb
  if limit>99: limit = 99 # TMP
  fields = 'trade_time t, close p' # TMP
  sql = f"select {fields} from '../../tmp/raw/{code}/*.parquet' ORDER BY t DESC LIMIT {limit}"
  df = duckdb.query(sql).df()
  if dump: print(df)
  else: return df.to_dict()

######################################

rt=tryx(lambda:eval(sys.stdin.readline(),{"__builtins__":{
  'o2s':o2s,
  'time_maker':time_maker,
  #'s2o':s2o,
  'now':now(),
  'help':"""NOTHING TO HELP.
PLEASE LEAVE IF YOU DONT UNDERSTAND
""",
  'count':count_by_code,
  'sample':sample_by_code,
}}),lambda v:v)
#print(o2s(rt))
if rt is not None: print(o2s(rt) if type(rt) in [dict,list] else
rt if type(rt) in [float,int,str] else
f'["function"]' if callable(rt) else
f'{[type(rt),rt]}' if rt is not None else '')

